<?php
// +---------------------------------------------------------------------+
// | NiuCloud | [ WE CAN DO IT JUST NiuCloud ]                |
// +---------------------------------------------------------------------+
// | Copy right 2019-2029 www.niucloud.com                          |
// +---------------------------------------------------------------------+
// | Author | NiuCloud <niucloud@outlook.com>                       |
// +---------------------------------------------------------------------+
// | Repository | https://github.com/niucloud/framework.git          |
// +---------------------------------------------------------------------+
namespace addon\wxoplatform\shop\controller;

use addon\weapp\model\Config as WeappConfigModel;
use addon\weapp\model\Config as WeappConfig;
use addon\weapp\model\Weapp;
use addon\wechat\model\Config as WechatConfigModel;
use addon\wxoplatform\model\Config as ConfigModel;
use addon\wxoplatform\model\OpenPlatform;
use app\model\upload\Upload;
use app\shop\controller\BaseShop;
use addon\wxoplatform\model\Oplatform as OplatformModel;

/**
 * 微信开放平台基础功能
 */
class Oplatform extends BaseShop
{
	
	/**
	 * 去授权
	 */
	public function auth()
	{
		$auth_type = input("auth_type", "wechat");//授权类型 wechat  公众号  weapp  小程序
		$oplatform_model = new OplatformModel();
		$callback = addon_url("wxoplatform://shop/oplatform/callback", [ "auth_type" => $auth_type ]);
		$result = $oplatform_model->getPreAuthorizationUrl([ "callback" => $callback ]);
		if ($result['code'] >= 0) {
			$this->redirect($result['data']);
		} else {
			$this->error($result['message']);
		}
	}
	
	/**
	 * 开放平台授权回调
	 */
	public function callback()
	{
		$auth_type = input("auth_type", "wechat");//授权类型 wechat  公众号  weapp  小程序
		$oplatform_model = new OplatformModel();
		$result = $oplatform_model->handleAuthorize();
		$error = '';
		$is_success = false;
		if ($result["code"] >= 0) {
			$arr = $result["data"]['authorization_info'];
			$config_model = new ConfigModel();
			$oplatform_result = $config_model->getOplatformConfig();
			$oplatform_config = $oplatform_result["data"];
			//拉取授权方账号信息
			$data = array(
				'authorizer_appid' => $arr["authorizer_appid"] ?? '',//授权方 appid
				'authorizer_access_token' => $arr["authorizer_access_token"] ?? '',//接口调用令牌（在授权的公众号/小程序具备 API 权限时，才有此返回值）
				'authorizer_refresh_token' => $arr["authorizer_refresh_token"] ?? '',//刷新令牌（在授权的公众号具备API权限时，才有此返回值），刷新令牌主要用于第三方平台获取和刷新已授权用户的 authorizer_access_token。一旦丢失，只能让用户重新授权，才能再次拿到新的刷新令牌。用户重新授权后，之前的刷新令牌会失效
				'is_authopen' => 1,//是否是开放平台授权,
				'component_appid' => $oplatform_config['value']['appid']
			);
			$auth_info_result = $oplatform_model->getAuthorizer([ "authorizer_appid" => $arr["authorizer_appid"] ]);
			$upload_model = new Upload();
			
			if ($auth_info_result["code"] >= 0) {
				if ($auth_info_result["data"]["authorizer_info"]["verify_type_info"]["id"] != -1) {
					// 查询授权是否已绑定
					$bound_info = model('config')->getInfo([ [ 'app_module', '=', 'shop' ], [ 'config_key', 'in', [ 'WECHAT_CONFIG', 'WEAPP_CONFIG' ] ], [ 'value', 'like', '%' . $data['authorizer_appid'] . '%' ] ], 'site_id');
					if (empty($bound_info) || $bound_info['site_id'] == $this->site_id) {
						if ($auth_type == "wechat") {//公众号授权
							$wechat_model = new \addon\wechat\model\Wechat();
							$auth_info = $auth_info_result["data"];
							$authorizer_info = $auth_info["authorizer_info"];//授权信息
							
							//拉取头像和二维码
							$headimg_result = $upload_model->setPath("headimg/wechat/" . date("Ymd") . '/', 'qrcode_' . $this->site_id . '.png')->remotePull($authorizer_info["head_img"]);
							$headimg = '';
							if ($headimg_result["code"] >= 0) {
								$headimg = $headimg_result["data"]["pic_path"];
							}
							
							$qrcode_url_result = $upload_model->setPath("qrcode/wechat/" . date("Ymd") . '/', 'qrcode_' . $this->site_id . '.png')->remotePull($authorizer_info["qrcode_url"]);
							
							$qrcode_path = '';
							if ($qrcode_url_result["code"] >= 0) {
								$qrcode_path = $qrcode_url_result["data"]["pic_path"];
							}
							$wechat_config_model = new WechatConfigModel();
							$data["service_type"] = $authorizer_info["service_type_info"];//公众号类型
							$data["verify_type"] = $authorizer_info["verify_type_info"];//公众号认证类型
							$data["service_type_info"] = $wechat_model->service_type[ $authorizer_info["service_type_info"]["id"] ];//公众号类型
							$data["verify_type_info"] = $wechat_model->verify_type[ $authorizer_info["verify_type_info"]["id"] ];//公众号认证类型
							$data["nick_name"] = $authorizer_info["nick_name"];//昵称
							$data["head_img"] = $headimg;//头像
							$data["user_name"] = $authorizer_info["user_name"];//原始 ID
							$data["principal_name"] = $authorizer_info["principal_name"];//主体名称
							$data["alias"] = $authorizer_info["alias"];//公众号所设置的微信号，可能为空
							$data["business_info"] = $authorizer_info["business_info"];//功能开通情况
							$data["qrcode_url"] = $qrcode_path;//二维码
							$res = $wechat_config_model->setWechatConfig($data, 1, $this->site_id);
							if ($res["code"] >= 0) {
								//成功
								$is_success = true;
								$this->assign('name', $authorizer_info["nick_name"]);
							}
							
						} else {
							$weapp_model = new Weapp();
							$weapp_config_model = new WeappConfigModel();
							$auth_info = $auth_info_result["data"];
							$authorizer_info = $auth_info["authorizer_info"];//授权信息
							
							//拉取头像和二维码
							$headimg_result = $upload_model->setPath("headimg/weapp/" . date("Ymd") . '/', 'qrcode_' . $this->site_id . '.png')->remotePull($authorizer_info["head_img"]);
							$headimg = '';
							if ($headimg_result["code"] >= 0) {
								$headimg = $headimg_result["data"]["pic_path"];
							}
							
							$qrcode_url_result = $upload_model->setPath("qrcode/weapp/" . date("Ymd") . '/', 'qrcode_' . $this->site_id . '.png')->remotePull($authorizer_info["qrcode_url"]);
							$qrcode_path = '';
							if ($qrcode_url_result["code"] >= 0) {
								$qrcode_path = $qrcode_url_result["data"]["pic_path"];
							}
							$data["service_type_info"] = $weapp_model->service_type[ $authorizer_info["service_type_info"]["id"] ];//小程序类型
							$data["verify_type_info"] = $weapp_model->verify_type[ $authorizer_info["verify_type_info"]["id"] ];//小程序认证类型
							$data["nick_name"] = $authorizer_info["nick_name"];//昵称
							$data["head_img"] = $headimg;//头像
							$data["user_name"] = $authorizer_info["user_name"];//原始 ID
							$data["principal_name"] = $authorizer_info["principal_name"];//主体名称
							$data["business_info"] = $authorizer_info["business_info"];//功能开通情况
							$data["qrcode_url"] = $qrcode_path;//二维码
							$data["signature"] = $authorizer_info["signature"];//帐号介绍
							$data["miniprograminfo"] = $authorizer_info["MiniProgramInfo"];//小程序配置，根据这个字段判断是否为小程序类型授权
							
							$res = $weapp_config_model->setWeappConfig($data, 1, $this->site_id);
							
							if ($res["code"] >= 0) {
								//成功
								$is_success = true;
								$this->assign('name', $authorizer_info["nick_name"]);
								
								//配置小程序合法域名
								$url = strstr(ROOT_URL, 'https://') === false ? str_replace('http', 'https', ROOT_URL) :  __ROOT__;
								$socket_url = str_replace('https', 'wss', $url);
								$network = array(
									'RequestDomain' => [ $url ],
									'WsRequestDomain' => [ $socket_url ],
									'UploadDomain' => [ $url ],
									'DownloadDomain' => [ $url ],
								);
								$data['miniprograminfo']['network'] = $network;
								$res = $weapp_config_model->setWeappConfig($data, 1, $this->site_id);
								$open_platform_model = new OpenPlatform($this->site_id);
								$data = array(
									'action' => 'set',
									'requestdomain' => $network['RequestDomain'],
									'wsrequestdomain' => $network['WsRequestDomain'],
									'uploaddomain' => $network['UploadDomain'],
									'downloaddomain' => $network['DownloadDomain'],
								);
								$open_platform_model->modifyDomain($data);
							}
						}
					} else {
						$error = $auth_type == 'wechat' ? '该公众号已授权给其他店铺' : '该小程序已授权给其他店铺';
					}
				} else {
					$error = $auth_type == 'wechat' ? '必须使用已认证的公众号进行授权' : '必须使用已认证的小程序进行授权';
				}
			}
		} else {
			$error = $result['message'];
		}
		$type_name = $auth_type == 'wechat' ? '公众号' : '小程序';
		$this->assign('type_name', $type_name);
		$this->assign("error", $error);//错误信息
		$this->assign("is_success", $is_success);//成功或失败
		//通知展示页
		return $this->fetch('oplatform/notify');
	}
	
	/**
	 * 微信公众号配置
	 */
	public function wechat()
	{
		$wechat_config_model = new WechatConfigModel();
		$config_result = $wechat_config_model->getWechatConfig($this->site_id);
		$this->assign("config", $config_result["data"]);
		return $this->fetch('oplatform/wechat');
	}
	
	/**
	 * 微信公众号授权绑定
	 */
	public function wechatSettled()
	{
		if (request()->isAjax()) {
			$wechat_config_model = new WechatConfigModel();
			$config_result = $wechat_config_model->getWechatConfig($this->site_id);
			$config = $config_result["data"];
			if (!empty($config["value"])) {
				return $wechat_config_model->success();
			} else {
				return $wechat_config_model->error();
			}
		} else {
			return $this->fetch('oplatform/wechat_settled');
		}
	}
	
	/**
	 * 微信公众号配置
	 */
	public function weapp()
	{
		$weapp_config_model = new WeappConfig();
		$config_result = $weapp_config_model->getWeappConfig($this->site_id);
		if (request()->isAjax()) {
			$RequestDomain = input('RequestDomain', []);
			$WsRequestDomain = input('WsRequestDomain', []);
			$UploadDomain = input('UploadDomain', []);
			$DownloadDomain = input('DownloadDomain', []);
			
			$value = $config_result['data']['value'] ?? [];
			$network = array(
				'RequestDomain' => $RequestDomain,
				'WsRequestDomain' => $WsRequestDomain,
				'UploadDomain' => $UploadDomain,
				'DownloadDomain' => $DownloadDomain,
			);
			
			$value['miniprograminfo']['network'] = $network;
			$res = $weapp_config_model->setWeAppConfig($value, 1, $this->site_id);
			$open_platform_model = new OpenPlatform($this->site_id);
			$data = array(
				'action' => 'set',
				'requestdomain' => $network['RequestDomain'],
				'wsrequestdomain' => $network['WsRequestDomain'],
				'uploaddomain' => $network['UploadDomain'],
				'downloaddomain' => $network['DownloadDomain'],
			);
			$result = $open_platform_model->modifyDomain($data);
			return $result;
		} else {
			
			$this->assign("config", $config_result["data"]);
			return $this->fetch('oplatform/weapp');
		}
	}
	
	/**
	 * 微信小程序授权绑定
	 */
	public function weappSettled()
	{
		if (request()->isAjax()) {
			$weapp_config_model = new WeappConfig();
			$config_result = $weapp_config_model->getWeappConfig($this->site_id);
			$config = $config_result["data"];
			if (!empty($config["value"])) {
				return $weapp_config_model->success();
			} else {
				return $weapp_config_model->error();
			}
		} else {
			return $this->fetch('oplatform/weapp_settled');
		}
		
	}
	
	public function notify()
	{
		$this->assign("is_success", 0);//成功或失败
		return $this->fetch('oplatform/notify');
	}
	
}